//
//  KFDLiveViewController.m
//  
//
//  Created by JIRENTIANXIANG on 6/20/15.
//
//

#import "KFDLiveViewController.h"
#import "KFDClient.h"
#import "KFDSettingsManager.h"
#import "KFDReachability.h"
#import "JTToast.h"
#import "KFDLoginViewController.h"
#import "KFDRegisterViewController.h"

#define LOGIN_URL @"objc://goToOCPage?typeid=1&typevalue=001"
#define REGISTER_URL @"objc://goToOCPage?typeid=1&typevalue=002"

@interface KFDLiveViewController ()<UIWebViewDelegate>

@property (strong,nonatomic) NSArray* rooms;
@property (strong,nonatomic) UIWebView* webView;
@property (copy,atomic) NSString* name;
@property (strong,atomic) NSURLRequest* request;
@property (copy,atomic) NSString* url;

@end

@implementation KFDLiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"直播";
    self.webView=[[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.allowsInlineMediaPlayback=YES;
    self.webView.delegate=self;
    [self.view addSubview:self.webView];
//    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header-switch-ico"] style:UIBarButtonItemStylePlain target:self action:@selector(switchButtonPressed)];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"refresh-ico"] style:UIBarButtonItemStylePlain target:self action:@selector(refreshButtonPressed)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
}

-(void)reachabilityChanged:(NSNotification*)note
{
    if (!self.url) {
        return;
    }
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    NetworkStatus status=curReach.currentReachabilityStatus;
    self.request=[NSURLRequest requestWithURL:[NSURL URLWithString:[self urlWithWifiOn:status==ReachableViaWiFi]]];
    [self.webView loadRequest:self.request];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        self.title=self.name;
//    });
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    KFDSettingsManager* settings=[KFDSettingsManager sharedManager];
    KFDReachability* reachability=[KFDReachability sharedReachability];
    if (settings.auxiliaryFunctionSettings.deny_video&&reachability.wifiStatus==NotReachable) {
        UIAlertController* alertController=[UIAlertController alertControllerWithTitle:nil message:@"您已设置在2G/3G/4G条件下禁止播放视频，如需播放请到我的-系统设置-辅助功能修改设置" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:ok];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        Reachability* wifiReach=[Reachability reachabilityForLocalWiFi];
        [wifiReach startNotifier];
        KFDClient* client=[KFDClient sharedClient];
        [client getLiveRoomsWithSuccessHandler:^(NSArray *rooms) {
            self.rooms=rooms;
            for (KFDLiveRoom* room in rooms) {
                if (room.isDefault) {
                    self.url=room.url;
                    self.name=room.name;
                    self.request=[NSURLRequest requestWithURL:[NSURL URLWithString:[self urlWithWifiOn:wifiReach.currentReachabilityStatus==ReachableViaWiFi]]];
                    [self.webView loadRequest:self.request];
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        self.title=room.name;
//                    });
                    break;
                }
            }
        } failureHandler:^(KFDResponseBody *response) {
            
        }];
    }
}

-(NSString*)urlWithWifiOn:(BOOL)wifiOn
{
    return [self.url stringByAppendingString:[NSString stringWithFormat:@"&iswifi=%@",@(wifiOn)]];
}

-(void)viewWillDisappear:(BOOL)animated
{
    Reachability* wifiReach=[Reachability reachabilityForLocalWiFi];
    [wifiReach stopNotifier];
}

//-(void)switchButtonPressed
//{
//    for (KFDLiveRoom* room in self.rooms) {
//        if (![self.name isEqualToString:room.name]) {
//            self.request=[NSURLRequest requestWithURL:[NSURL URLWithString:room.url]];
//            [self.webView loadRequest:self.request];
//            self.name=room.name;
//            self.title=room.name;
//            break;
//        }
//    }
//}

-(void)refreshButtonPressed
{
    [self.webView loadRequest:self.request];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL* url=request.URL;
    NSString* path=url.absoluteString;
    if ([path isEqualToString:LOGIN_URL]) {
        KFDLoginViewController* loginVC=[[UIStoryboard storyboardWithName:@"KFDLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"KFDLoginViewController"];
        loginVC.sourceViewController=self;
        [self.navigationController pushViewController:loginVC animated:YES];
    }else if ([path isEqualToString:REGISTER_URL]){
        KFDRegisterViewController* registerVC=[[UIStoryboard storyboardWithName:@"KFDRegister" bundle:nil] instantiateViewControllerWithIdentifier:@"KFDRegisterViewController"];
        registerVC.sourceViewController=self;
        [self.navigationController pushViewController:registerVC animated:YES];
    }
    return YES;
}

@end
